<script setup lang="ts">
const directStore = useDirectStore();
const appStore = useAppStore();

const fileList = ref([]);

const fetchFiles = async () => {
  const response = await DirectService.queryOrderFile({
    orderId: directStore.directDetailObj.orderId,
  });
  // 转换格式：将 picUrl 映射为 url，并添加必要的字段供 up-upload 组件显示
  fileList.value = response.map((item: any) => ({
    ...item,
    url: item.picUrl,
  }));
};

const handleDelete = async (item: any) => {
  uni.showModal({
    content: '是否确认删除该文件',
    success: async (res: any) => {
      if (res.confirm) {
        await DirectService.delPicture({ picId: item.file.picId });
        showSuccess('删除成功');
        appStore.setHadDoneOnDetail(true);
        fetchFiles();
      }
    },
  });
};

const handleAfterRead = async (event: any) => {
  // 获取新上传的文件列表
  const lists = Array.isArray(event.file) ? event.file : [event.file];

  // 直接上传新文件，不需要操作 fileList
  const imageUrls = await uploadFiles(lists);

  // 并行保存所有图片到服务器
  await Promise.all(
    imageUrls.map(picUrl =>
      DirectService.addPicture({
        orderId: directStore.directDetailObj.orderId,
        picUrl,
      })
    )
  );

  showSuccess('上传成功');
  // 重新获取文件列表，更新显示
  fetchFiles();
  appStore.setHadDoneOnDetail(true);
};

const handlePreview = (file: any) => {
  // 手动调用预览图片
  uni.previewImage({
    current: file.index || 0, // 当前图片索引
    urls: fileList.value.map((item: any) => item.url), // 所有图片 URL 列表
  });
};

onMounted(() => {
  fetchFiles();
});
</script>

<template>
  <view class="px-4 pt-10">
    <view class="text-17 flex font-bold">
      <view>图片</view>
      <view class="color-main-3">附件</view>
    </view>
    <view class="view-shadow p-4">
      <up-upload
        :fileList="fileList"
        @delete="handleDelete"
        @afterRead="handleAfterRead"
        :previewFullImage="true"
        @clickPreview="handlePreview"
        multiple
        upload-icon="plus"
        class="block mt-2"
      />
    </view>
  </view>
</template>
